require(["./config"], () => {
    require(["template","url","header","footer","main","fly"], (template,url) =>{
        class Shopping {
            constructor () {
                this.render()
                this.calculateMoney()
                this.checksChange()
                this.setAllCheckBtn()
            }
            render () {
                const cart = localStorage.getItem('cart')
                if (cart) {
                    this.cart = JSON.parse(cart)
                    $('#cart-things').html(template('cartTemplate', { cart: this.cart }))
                } else {
                    // 购物车为空
                    $('#shopping').hide()
                    $('#donBuy').show()
                }
            }
            calculateMoney () {
                let totalMoney = this.cart.reduce((total, shop) => {
                    if (shop.checked) total += shop.price * shop.count
                    return total
                }, 0)
                $('#Paymoney').html(totalMoney.toFixed(2))
            }
            checksChange () {
                const _this = this
                $('.checks').on('change', function () {
                    const id = $(this).parents('tr').data('id')
                    _this.cart = _this.cart.map(shop => {
                        if (shop.id === id) shop.checked = $(this).prop('checked')
                        return shop
                    })
                    localStorage.setItem('cart', JSON.stringify(_this.cart))
                    _this.calculateMoney()
                    _this.setAllCheckBtn()
                })
            }
            setAllCheckBtn () {
                const isAllCheck = this.cart.every(shop => shop.checked)
                $('#all-check').prop('checked', isAllCheck)
            }
        }
        new Shopping()
    })
})